package com.bookstore.common.validation;

import cn.hutool.core.util.StrUtil;
import com.bookstore.common.constant.UserConstants;
import com.bookstore.common.exception.ValidationException;
import com.bookstore.common.exception.UserStatusException;
import com.bookstore.common.exception.AuthenticationException;
import com.bookstore.common.util.PasswordUtil;
// 移除具体的DTO和Entity依赖，使用通用接口

import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 认证验证工具类
 * 提供集中的参数验证逻辑
 */
public class AuthValidationUtil {

    /**
     * 邮箱格式正则表达式
     */
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
            "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"
    );

    /**
     * 手机号格式正则表达式（中国大陆）
     */
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    /**
     * 用户名格式正则表达式（4-20位字母数字下划线）
     */
    private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_]{4,20}$");

    /**
     * 验证登录请求参数
     */
    public static ValidationResult validateLoginRequest(String username, String password) {
        if (StrUtil.isBlank(username)) {
            return ValidationResult.failure("用户名不能为空", "AUTH_002", "username");
        }

        if (StrUtil.isBlank(password)) {
            return ValidationResult.failure("密码不能为空", "AUTH_003", "password");
        }

        if (password.length() < 6 || password.length() > 20) {
            return ValidationResult.failure("密码长度必须在6-20位之间", "AUTH_004", "password");
        }

        return ValidationResult.success();
    }

    /**
     * 验证注册请求参数
     */
    public static ValidationResult validateRegisterRequest(String username, String password, 
            String confirmPassword, String phone, String email, Integer userType) {
        
        // 验证用户名
        ValidationResult usernameResult = validateUsername(username);
        if (!usernameResult.isValid()) {
            return usernameResult;
        }

        // 验证密码
        ValidationResult passwordResult = validatePassword(password);
        if (!passwordResult.isValid()) {
            return passwordResult;
        }

        // 验证确认密码
        if (!Objects.equals(password, confirmPassword)) {
            return ValidationResult.failure("两次输入的密码不一致", "AUTH_006", "confirmPassword");
        }

        // 验证手机号（如果提供）
        if (StrUtil.isNotBlank(phone)) {
            ValidationResult phoneResult = validatePhone(phone);
            if (!phoneResult.isValid()) {
                return phoneResult;
            }
        }

        // 验证邮箱（如果提供）
        if (StrUtil.isNotBlank(email)) {
            ValidationResult emailResult = validateEmail(email);
            if (!emailResult.isValid()) {
                return emailResult;
            }
        }

        // 验证用户类型
        ValidationResult userTypeResult = validateUserType(userType);
        if (!userTypeResult.isValid()) {
            return userTypeResult;
        }

        return ValidationResult.success();
    }

    /**
     * 验证用户名格式
     */
    public static ValidationResult validateUsername(String username) {
        if (StrUtil.isBlank(username)) {
            return ValidationResult.failure("用户名不能为空", "AUTH_007", "username");
        }

        if (!USERNAME_PATTERN.matcher(username).matches()) {
            return ValidationResult.failure("用户名格式不正确，只能包含字母、数字和下划线，长度4-20位", "AUTH_008", "username");
        }

        return ValidationResult.success();
    }

    /**
     * 验证密码格式
     */
    public static ValidationResult validatePassword(String password) {
        if (StrUtil.isBlank(password)) {
            return ValidationResult.failure("密码不能为空", "AUTH_009", "password");
        }

        if (password.length() < 6 || password.length() > 20) {
            return ValidationResult.failure("密码长度必须在6-20位之间", "AUTH_010", "password");
        }

        // 可以添加更复杂的密码强度验证
        return ValidationResult.success();
    }

    /**
     * 验证手机号格式
     */
    public static ValidationResult validatePhone(String phone) {
        if (StrUtil.isBlank(phone)) {
            return ValidationResult.failure("手机号不能为空", "AUTH_011", "phone");
        }

        if (!PHONE_PATTERN.matcher(phone).matches()) {
            return ValidationResult.failure("手机号格式不正确", "AUTH_012", "phone");
        }

        return ValidationResult.success();
    }

    /**
     * 验证邮箱格式
     */
    public static ValidationResult validateEmail(String email) {
        if (StrUtil.isBlank(email)) {
            return ValidationResult.failure("邮箱不能为空", "AUTH_013", "email");
        }

        if (!EMAIL_PATTERN.matcher(email).matches()) {
            return ValidationResult.failure("邮箱格式不正确", "AUTH_014", "email");
        }

        return ValidationResult.success();
    }

    /**
     * 验证用户类型
     */
    public static ValidationResult validateUserType(Integer userType) {
        if (userType == null) {
            return ValidationResult.failure("用户类型不能为空", "AUTH_015", "userType");
        }

        if (!Objects.equals(userType, UserConstants.USER_TYPE_NORMAL) && 
            !Objects.equals(userType, UserConstants.USER_TYPE_MERCHANT)) {
            return ValidationResult.failure("用户类型不正确", "AUTH_016", "userType");
        }

        return ValidationResult.success();
    }

    /**
     * 验证用户状态
     */
    public static void validateUserStatus(Long userId, String username, Integer status) {
        if (status == null) {
            throw new AuthenticationException("用户状态信息不存在");
        }

        if (!Objects.equals(UserConstants.USER_STATUS_NORMAL, status)) {
            String reason = Objects.equals(UserConstants.USER_STATUS_DISABLED, status) 
                    ? "账号已禁用" : "账号已锁定";
            throw new UserStatusException(reason, userId, username, status);
        }
    }

    /**
     * 验证密码
     */
    public static void validatePassword(String inputPassword, String salt, String hashedPassword) {
        if (StrUtil.isBlank(inputPassword)) {
            throw new ValidationException("密码不能为空", "password", null, null);
        }

        if (!PasswordUtil.verifyPassword(inputPassword, salt, hashedPassword)) {
            throw new AuthenticationException("用户名或密码错误");
        }
    }

    /**
     * 抛出验证异常（如果验证失败）
     */
    public static void throwIfInvalid(ValidationResult result) {
        if (!result.isValid()) {
            throw new ValidationException(result.getErrorCode(), result.getErrorMessage(), result.getFieldName(), null);
        }
    }
}